package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.common.Result;
import com.zhentao.dto.QrCodeScanRequest;
import com.zhentao.pojo.InspectionTask;
import com.zhentao.pojo.QrCodeScan;
import com.zhentao.pojo.VehicleInfo;
import com.zhentao.service.InspectionTaskService;
import com.zhentao.service.QrCodeScanService;
import com.zhentao.service.VehicleInfoService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码扫描控制器
 */
@RestController
@RequestMapping("/api/qrcode")
@CrossOrigin
public class QrCodeController {

    @Autowired
    private QrCodeScanService qrCodeScanService;

    @Autowired
    private VehicleInfoService vehicleInfoService;

    @Autowired
    private InspectionTaskService inspectionTaskService;

    /**
     * 扫描二维码
     */
    @PostMapping("/scan")
    public Result<Map<String, Object>> scanQrCode(@RequestBody QrCodeScanRequest request,
                                                  HttpServletRequest httpRequest) {
        try {
            // 创建扫描记录
            QrCodeScan scanRecord = new QrCodeScan();
            scanRecord.setQrContent(request.getQrContent());
            scanRecord.setQrType(request.getQrType() != null ? request.getQrType() : "OTHER");
            scanRecord.setScanLocation(request.getScanLocation());
            scanRecord.setDeviceInfo(request.getDeviceInfo());
            scanRecord.setIpAddress(getClientIpAddress(httpRequest));
            scanRecord.setCreateTime(new Date());

            // 解析二维码内容
            Map<String, Object> result = parseQrContent(request.getQrContent(), request.getQrType());

            if (result.get("success").equals(true)) {
                scanRecord.setScanResult("SUCCESS");
                scanRecord.setTargetId((Long) result.get("targetId"));
            } else {
                scanRecord.setScanResult("FAILED");
                scanRecord.setErrorMessage((String) result.get("message"));
            }

            // 保存扫描记录
            qrCodeScanService.save(scanRecord);

            return Result.success("扫描成功", result);

        } catch (Exception e) {
            // 保存失败记录
            QrCodeScan scanRecord = new QrCodeScan();
            scanRecord.setQrContent(request.getQrContent());
            scanRecord.setQrType(request.getQrType() != null ? request.getQrType() : "OTHER");
            scanRecord.setScanResult("FAILED");
            scanRecord.setErrorMessage(e.getMessage());
            scanRecord.setCreateTime(new Date());
            qrCodeScanService.save(scanRecord);

            return Result.error("扫描失败：" + e.getMessage());
        }
    }

    /**
     * 获取扫描历史
     */
    @GetMapping("/history")
    public Result<Object> getScanHistory(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       @RequestParam(required = false) Long userId) {
        try {
            // 这里可以根据userId查询用户的扫描历史
            // 暂时返回所有记录，实际应用中需要根据用户权限过滤
            return Result.success("查询成功", qrCodeScanService.list());
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 解析二维码内容
     */
    private Map<String, Object> parseQrContent(String qrContent, String qrType) {
        Map<String, Object> result = new HashMap<>();

        try {
            if ("VEHICLE".equals(qrType)) {
                // 解析车辆二维码，假设格式为：VEHICLE:车牌号
                if (qrContent.startsWith("VEHICLE:")) {
                    String licensePlate = qrContent.substring(8);
                    // 通过查询条件获取车辆信息
                    QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("license_plate", licensePlate);
                    queryWrapper.eq("status", 1);
                    VehicleInfo vehicle = vehicleInfoService.getOne(queryWrapper);

                    if (vehicle != null) {
                        result.put("success", true);
                        result.put("type", "VEHICLE");
                        result.put("targetId", vehicle.getId());
                        result.put("data", vehicle);
                        result.put("message", "车辆信息获取成功");
                    } else {
                        result.put("success", false);
                        result.put("message", "未找到车辆信息");
                    }
                } else {
                    result.put("success", false);
                    result.put("message", "车辆二维码格式错误");
                }

            } else if ("TASK".equals(qrType)) {
                // 解析任务二维码，假设格式为：TASK:任务编号
                if (qrContent.startsWith("TASK:")) {
                    String taskNo = qrContent.substring(5);
                    // 通过查询条件获取任务信息
                    QueryWrapper<InspectionTask> taskQueryWrapper = new QueryWrapper<>();
                    taskQueryWrapper.eq("task_no", taskNo);
                    InspectionTask task = inspectionTaskService.getOne(taskQueryWrapper);

                    if (task != null) {
                        result.put("success", true);
                        result.put("type", "TASK");
                        result.put("targetId", task.getId());
                        result.put("data", task);
                        result.put("message", "任务信息获取成功");
                    } else {
                        result.put("success", false);
                        result.put("message", "未找到任务信息");
                    }
                } else {
                    result.put("success", false);
                    result.put("message", "任务二维码格式错误");
                }

            } else {
                // 其他类型的二维码
                result.put("success", true);
                result.put("type", "OTHER");
                result.put("data", qrContent);
                result.put("message", "二维码内容：" + qrContent);
            }

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "解析二维码失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }
}
